import fs from 'fs'
import path from 'path'
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// 配置参数
const SVG_DIR = path.join(__dirname, '../src/assets/svg') // SVG 存放目录

// 更改内容
function generateSingleFile (content, fileName) {

    const updateContent = content.replace(/width="[^"]*"/g, 'width={width?width:size}')
        .replace(/height="[^"]*"/g, 'height={height?height:size}')
        .replace(/style="[^"]*"/g, '')
        .replace(/t="[^"]*"/g, '')
        .replace(/class="[^"]*"/g, '')
        .replace(/xmlns="[^"]*"/g, '')
        .replace(/xmlns:xlink="[^"]*"/g, '')

    return `
    import type { SvgIconProps } from './interface'
        export const ${fileName}: React.FC<SvgIconProps> = ({ size = 16, width, height }) => {
    return ${updateContent}
    }
    `
}
// 读取生成文件
function fileOperate (inputPath, targetPath, fileName) {
    if (!inputPath || !targetPath) return
    fs.readFile(inputPath, 'utf8', (err, data) => {
        if (err) {
            console.error('读取文件时出错:', err);
            return;
        }

        const processedContent = generateSingleFile(data, fileName)

        fs.writeFileSync(targetPath, processedContent, 'utf8', (err) => {
            if (err) {
                console.error('写入文件时出错:', err);
                return;
            }
            console.log('文件处理完成，新文件已生成:', targetPath);
        });
    })


}

// main
function generateSvgReactFC () {
    try {
        // 获取所有 SVG 文件名
        const files = fs.readdirSync(SVG_DIR)
            .filter(file => file.endsWith('.svg'))
            .map(file => file.replace('.svg', ''))

        files.forEach(file => {
            const newName = `${file.replace(/^./, str => str.toUpperCase())}SvgFC`
            const inputPath = path.join(SVG_DIR, `${file}.svg`)
            const targetPath = path.join(SVG_DIR, `${newName}.tsx`)
            fileOperate(inputPath, targetPath, newName)
        })

    } catch {
        console.log("错误");

    }
}

generateSvgReactFC()